package controllers

import (
	"erp/models"
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// GetSystemSettings 获取系统设置
func GetSystemSettings(c *gin.Context, db *gorm.DB) {
	var settings []models.SystemSetting
	db.Find(&settings)

	// 转换为更易于前端使用的格式
	settingsMap := make(map[string]string)
	for _, setting := range settings {
		settingsMap[setting.SettingKey] = setting.SettingValue
	}

	c.JSON(http.StatusOK, settingsMap)
}

// UpdateSystemSetting 更新单个系统设置
func UpdateSystemSetting(c *gin.Context, db *gorm.DB) {
	// 绑定请求参数
	var requestData struct {
		Key   string `json:"key" binding:"required"`
		Value string `json:"value" binding:"required"`
	}

	if err := c.ShouldBindJSON(&requestData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}

	// 查找设置
	var setting models.SystemSetting
	result := db.Where("setting_key = ?", requestData.Key).First(&setting)

	if result.Error != nil {
		// 不存在则创建
		setting = models.SystemSetting{
			SettingKey:   requestData.Key,
			SettingValue: requestData.Value,
		}
		db.Create(&setting)
	} else {
		// 存在则更新
		setting.SettingValue = requestData.Value
		db.Save(&setting)
	}

	c.JSON(http.StatusOK, gin.H{"message": "设置已更新"})
}
